<script setup lang="tsx">
import { ElButton, ElSwitch } from 'element-plus'
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { FormSchema } from '@/components/Form'
import { Table, TableColumn } from '@/components/Table'
import { ElMessage, ElDatePicker, ElInput } from 'element-plus'

import { useSearch } from '@/hooks/web/useSearch'
import { useTable } from '@/hooks/web/useTable'
import { ref, reactive, unref } from 'vue'
import { getAllUserApi, banUserApi, GetExportAllUserApi } from '@/api/user'
import { useI18n } from '@/hooks/web/useI18n'
import { computed } from 'vue'
import { useUserStore } from '@/store/modules/user'
import { useDownload } from '@/utils/is'

import ProportionDialog from './components/ProportionDialog.vue'
import EarningsDialog from './components/EarningsDialog.vue'

const { t } = useI18n()

const userStore = useUserStore()

//formSchema
const { searchRegister, searchMethods } = useSearch()
const { getFormData: getSearchFormData, setValues: setSearchFormData } = searchMethods
const schema = reactive<FormSchema[]>([
  {
    field: 'userName',
    label: '用户名称',
    component: 'Input'
  },
  {
    field: 'levelId',
    label: '用户级别',
    component: 'Select',
    componentProps: {
      options: [
        {
          label: '一级',
          value: '1'
        },
        {
          label: '二级',
          value: '2'
        },
        {
          label: '三级',
          value: '3'
        },
        {
          label: '四级',
          value: '4'
        }
      ]
    }
  },
  {
    field: 'advertisingNum',
    label: '观看广告条数',
    component: 'Input',
    formItemProps: {
      slots: {
        default: (formData) => {
          return (
            <div>
              <ElInput
                v-model={formData.beginAdvertisingNum}
                placeholder="开始广告数量"
                style={{ width: '150px' }}
              />
              <span style={{ margin: '0 10px' }}>至</span>
              <ElInput
                v-model={formData.endAdvertisingNum}
                placeholder="结束广告数量"
                style={{ width: '150px' }}
              />
            </div>
          )
        }
      }
    }
  },
  {
    field: 'time',
    label: '注册时间',
    component: 'DatePicker',
    formItemProps: {
      slots: {
        default: (formData) => {
          const times = computed({
            get: () => {
              if (formData.beginTime && formData.endTime) {
                return [formData.beginTime, formData.endTime]
              } else {
                return []
              }
            },
            set: (times) => {
              if (times) {
                formData.beginTime = times[0]
                formData.endTime = times[1]
              } else {
                formData.beginTime = undefined
                formData.endTime = undefined
              }
            }
          })
          return (
            <ElDatePicker
              v-model={times.value}
              type="daterange"
              valueFormat="YYYY-MM-DD"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              placeholder="选择日期范围"
            />
          )
        }
      }
    }
  }
])
//Table

const { tableRegister, tableMethods, tableState } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const searchFormData = await getSearchFormData()
    const { data, count } = await getAllUserApi({
      pageNo: unref(currentPage),
      pageSize: unref(pageSize),
      ...searchFormData,
      recordId: userStore.getAppId
    })
    return {
      list: data,
      total: count
    }
  }
})

const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList } = tableMethods

const isShow = ref(false)
const curItemIndex = ref(1)
const proportionDialogRef = ref()
const earningsDialogRef = ref()

const isShowUserName = (row: any) => {
  curItemIndex.value = row.id
  isShow.value = true
  setTimeout(() => {
    isShow.value = false
  }, 30000)
}

const columns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index'
  },
  {
    field: 'createTime',
    label: '注册日期'
  },
  {
    field: 'userName',
    label: '用户名称'
  },
  {
    field: 'code',
    label: '用户ID',
    slots: {
      default: ({ row }) => {
        return (
          <div>
            {curItemIndex.value === row.id && isShow.value ? (
              row.code
            ) : (
              <span style={'color:blue'} onClick={() => isShowUserName(row)}>
                点击查看
              </span>
            )}
          </div>
        )
      }
    }
  },
  {
    field: 'pname',
    label: '所属合伙人'
  },
  {
    field: 'totalGoldNum',
    label: '总广告收益'
  },
  {
    field: 'advertisingNum',
    label: '观看广告条数'
  },
  {
    field: 'loginIp',
    label: 'IP地址'
  },
  {
    field: 'loginTime',
    label: '最近登录'
  },
  {
    field: 'status',
    label: '启用/禁用',
    slots: {
      default: ({ row }: any) => {
        return (
          <ElSwitch
            v-model={row.status}
            activeValue={1}
            inactiveValue={0}
            onChange={(val: boolean) => {
              banUserApi({
                id: row.id,
                status: val ? 1 : 0
              }).then(() => {
                getList()
                ElMessage.success('操作成功')
              })
            }}
          ></ElSwitch>
        )
      }
    }
  },
  {
    field: 'action',
    label: t('tableDemo.action'),
    width: 280,
    slots: {
      default: ({ row }) => {
        return (
          <div class="flex gap-1">
            <ElButton
              type="primary"
              size="small"
              onClick={() => proportionDialogRef.value.openDialog(row)}
            >
              {{
                default: () => '分成记录'
              }}
            </ElButton>
            <ElButton
              type="primary"
              size="small"
              onClick={() => earningsDialogRef.value.openDialog(row)}
            >
              {{
                default: () => '收益记录'
              }}
            </ElButton>
          </div>
        )
      }
    }
  }
])
// 重置搜索
const onResetSearch = () => {
  setSearchFormData({
    beginTime: null,
    endTime: null,
    beginAdvertisingNum: '',
    endAdvertisingNum: ''
  })
  getList()
}
const handleExport = async () => {
  const searchFormData = await getSearchFormData()
  useDownload(GetExportAllUserApi, `所有用户`, { recordId: userStore.getAppId, ...searchFormData })
}
</script>

<template>
  <ContentWrap title="所有用户">
    <Search :schema="schema" @search="getList" @reset="onResetSearch" @register="searchRegister" />
    <div class="flex justify-end mb-[10px]">
      <BaseButton type="primary" @click="handleExport">导出</BaseButton>
    </div>
    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="columns"
      :data="dataList"
      row-key="id"
      :loading="loading"
      sortable
      headerAlign="center"
      align="center"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
    />
    <ProportionDialog ref="proportionDialogRef" />
    <EarningsDialog ref="earningsDialogRef" />
  </ContentWrap>
</template>
